<template>
	<div class="aid">

		<div class="base">
			<p class="fixed-top">
				{{ JSON.stringify(text) == '{}' ? '添加角色' : '修改角色' }}
				<a-icon @click="closeFunction" type="close" />
			</p>
			<div class="main" id="new_message">
				<a-form-model ref="ruleForm" :model="form" :rules="rules">
					<a-form-model-item label="名称" prop="Name">
						<a-input v-model="form.Name" />
					</a-form-model-item>
					<a-form-model-item label="权限" prop="PowerData">
						<tree :treeDate="treeDate" :treeValue="treeValue" @func="getMsgFormSon"></tree>
						<!-- <a-button @click="showtreeIf = !showtreeIf">选择</a-button>
						<div class="treeshow" v-show="showtreeIf">
							<tree :treeDate="treeDate" :treeValue="treeValue" @func="getMsgFormSon"></tree>
						</div> -->
					</a-form-model-item>
					<a-form-model-item label="" class="fixed-bottom">
						<a-button type="primary" @click="handleSubmit">
							{{ JSON.stringify(text) == '{}' ? '确认添加' : '确认修改' }}
						</a-button>
						<a-button style="margin-left: 10px;" @click="closeFunction">取消</a-button>
					</a-form-model-item>
				</a-form-model>
				<el-table :data="treetableDate" row-key="value" border default-expand-all max-height="450"
					:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="width:96%;margin:0 2%;">
					<el-table-column prop="title" label="名称" width="360"></el-table-column>
					<el-table-column prop="ModuleName" label="权限" min-width="160">
						<template slot-scope="scope">
							<div class="typelist" v-if="scope.row.BindKey">
								<div>
									<h4>角色模块权限<a-button class="editbutton" v-if="scope.row.BindKey"
											@click="GetListByKeyFun(text.ID,scope.row)">编辑</a-button>
										<a-select v-if="scope.row.BindKey && scope.row.edit"
											@change="e=>depertFun(text.ID,scope.row,e)" style="width:200px;"
											:allowClear="true" v-decorator="['departCode']" optionFilterProp="children"
											showSearch size="small">
											<a-select-option v-for="(item, index) in scope.row.DepartCodeList"
												:key="index" :value="item.Code">{{ item.Name }}</a-select-option>
										</a-select>
									</h4>

								</div>
								<div class="flex">
									<span class="list" v-for="(item,i) in scope.row.moduleList" :key="i">
										<span class="listspan">{{ item.Name }}</span>
										<i @click="deleteList(text.ID,scope.row,item)" class="el-icon-delete"></i>
									</span>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindActivityFlow">
								<div>
									<h4>活动审批权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RoleActivity','活动审批权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindCreditFlow">
								<div>
									<h4>积分申请审批权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RoleCreditFlow','积分申请审批权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindSendRecordExam">
								<div>
									<h4>积分发放审批权限<a-button class="editbutton"
											@click="RoleCreditSendExamFun(text.ID,scope.row,'RoleCreditSendExam')">查看
										</a-button>
										<a-button class="editbutton"
											@click="AddRoleCreditSendExamFun(text.ID,scope.row,'RoleCreditSendExam')">新增
										</a-button>
									</h4>
								</div>
								<div class="flex">
									<span class="list" v-for="(item,i) in scope.row.BindSendRecordExamList" :key="i">
										<span class="listspan">{{ item.ActivityTypeName }}</span>
										<i @click="RoleCreditSendExamdeleteList(text.ID,scope.row,item)"
											class="el-icon-delete"></i>
									</span>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindPracticeFlow">
								<div>
									<h4>社会实践审批权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RolePracticeTeam','社会实践审批权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindActivity">
								<div>
									<h4>活动管理权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RoleActivityManage','活动管理权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindActivityEndFlow">
								<div>
									<h4>活动完结审批权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RoleActivity','活动完结审批权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindPracticeDeclareFlow">
								<div>
									<h4>社会实践结项权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RolePracticeTeam','社会实践结项权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
							<div class="typelist" v-if="scope.row.BindClubAnnualAuditFlow">
								<div>
									<h4>组织年审审批权限<a-button class="editbutton"
											@click="GetListByKeyActivityFun(text.ID,scope.row,'RoleClubAnnualAuditFlow','组织年审审批权限')">查看
										</a-button>
									</h4>
								</div>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<AddRoleCreditSendExam :text="AddRoleCreditSendExamText" v-show="AddRoleCreditSendExamIf"
			:ActivityFlowTypeList="ActivityFlowTypeList" @closeFun="AddRoleCreditSendExamcloseFun">
		</AddRoleCreditSendExam>
		<a-modal v-model:visible="visible" :title="modeltitle" width="800px" @cancel="handleCancel">
			<template #footer>
				<a-button key="back" @click="handleCancel">关闭</a-button>
			</template>
			<RoleCreditFlow ref="RoleCreditFlow1" v-show="RoleCreditFlowIf"></RoleCreditFlow>
			<RoleActivityManage ref="RoleActivityManage1" v-show="RoleActivityManageIf"></RoleActivityManage>
			<RoleActivity ref="RoleActivity1" v-show="RoleActivityIf"></RoleActivity>
			<RolePracticeTeam ref="RolePracticeTeam1" v-show="RolePracticeTeamIf"></RolePracticeTeam>
			<RoleClubAnnualAuditFlow ref="RoleClubAnnualAuditFlow1" v-show="RoleClubAnnualAuditFlowIf"></RoleClubAnnualAuditFlow>
			
		</a-modal>
	</div>
</template>

<script>
	import tree from '@/components/tree/tree.vue'
	import AddRoleCreditSendExam from "@/views/Role/RoleCreditSendExam/add.vue"
	import RoleActivity from "@/views/RoleActivity/index.vue"
	import RoleActivityManage from "@/views/RoleActivityManage/index.vue"
	import RoleCreditFlow from "@/views/Role/RoleCreditFlow/index.vue"
	import RolePracticeTeam from "@/views/Role/RolePracticeTeam/index.vue"
	import RoleClubAnnualAuditFlow from "@/views/Role/RoleClubAnnualAuditFlow/index.vue"
	import {
		AddRole,
		UpdateRole,
		GetDepartList,
		ManageRoleModuleDoAddRoleModule,
		ManageRoleModuleDoGetListByKey,
		ManageRoleModuleDoDeleteRoleModule,
		ManageRoleCreditSendExamDoGetList,
		ManageRoleCreditSendExamDoDelete
	} from '@/api/follow';
	export default {
		components: {
			tree,
			AddRoleCreditSendExam,
			RoleActivity,
			RoleActivityManage,
			RolePracticeTeam,
			RoleClubAnnualAuditFlow,
			RoleCreditFlow
		},
		props: {
			text: Object,
			treeDate: Array,
			timer: Number
		},
		watch: {
			timer: function(text) {
				let arr = [...this.treeDate];
				this.originDate = this.deep(arr)
				this.originDate.forEach(item => {
					this.$set(item, 'moduleList', [])
					this.$set(item, 'edit', false)
					this.$set(item, 'DepartCodeList', [])
					this.$set(item, 'BindSendRecordExamList', [])
					// item = Object.assign({}, item, {moduleList: [], edit: false,DepartCodeList:[],BindSendRecordExamList:[]})
				})
				if (this.text.ID) {
					let that = this
					this.form = this.text;
					this.oldName = this.text.Name
					this.oldPower = this.form.PowerData
					that.treeValue = that.form.PowerData.split(',')
					that.getMsgFormSon(that.treeValue,1)
					// that.tableFun(that.treeValue, [], [])
				} else {

				}
			}
		},
		data() {
			return {
				RoleClubAnnualAuditFlowIf:false,
				modeltitle:'',
				RoleCreditFlowIf: false,
				RoleActivityManageIf: false,
				RoleActivityIf: false,
				RolePracticeTeamIf: false,
				originDate: [],
				showtreeIf: false,
				treetableDate: [],
				loading: false,
				formLayout: 'horizontal',
				form: this.$form.createForm(this, {
					name: 'coordinated'
				}),
				treeValue: [],
				power: [],
				form: {
					Name: '',
					PowerData: '',
				},
				rules: {
					Name: [{
						required: true,
						message: '请输入角色名称',
						trigger: 'change'
					}],
					PowerData: [{
						required: true,
						message: '请选择权限',
						trigger: 'change'
					}],
				},
				DepartCodeList: [],
				currentTableData: [],
				AddRoleCreditSendExamText: {},
				AddRoleCreditSendExamIf: false,
				ActivityFlowTypeList: [],
				roleID: '',
				row: {},
				oldName: '',
				oldPower: '',
				changeData: 0,
				visible: false
			};
		},
		created() {

		},
		methods: {
			//根据选中的value渲染表格，尼玛，太烦人了，卧槽，老子不想写了
			tableFun(ids, ids1, ids2) {
				let arr = [...this.originDate]
				let arr2 = [...ids, ...ids1, ...ids2]
				let arr1 = Array.from(new Set(arr2))
				let newArr = []
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0; j < arr1.length; j++) {
						if (arr1[j] == arr[i].value) {
							newArr.push(arr[i])
						}
					}
				}
				let arr3 = Array.from(newArr)
				this.currentTableData = arr3
				if (this.treetableDate.length > 0) {
					for (let i = 0; i < this.treetableDate.length; i++) {
						for (let j = 0; j < this.treetableDate[i].children.length; j++) {
							for (let p = 0; p < this.treetableDate[i].children[j].children.length; p++) {
								this.treetableDate[i].children[j].children[p].children = []
							}
							this.treetableDate[i].children[j].children = []
						}
						this.treetableDate[i].children = []
					}
					this.treetableDate = []
				}

				this.treetableDate = this.toTree(arr3)
			},
			recursion(data) {
				data.forEach(item => {
					if (item.children.length === 0) {
						delete item.children
					} else {
						this.recursion(item.children)
					}
				});
			},
			filterArr(opArr) {
				function circle(opArr) {
					for (let i = 0; i < opArr.length; i++) {
						if (opArr[i].children) {
							opArr.splice(i, 1)
							i--
						} else if (opArr[i].children && opArr[i].children.length) {
							circle(opArr[i].children)
						}
					}
				}
				circle(opArr)
				return opArr
			},
			//获取绑定的部门，点击获取一次，删除成功获取一次，选中下拉框之后获取一次，卧槽，好烦
			async GetListByKeyFun(roleID, row) {
				this.checkChange()
				row.edit = true
				let res = await ManageRoleModuleDoGetListByKey({
					roleID: roleID,
					bindKey: row.BindKey
				});
				row.moduleList = res.data.data.filter(m => m.Value)
				row.DepartCodeList = res.data.data.filter(m => !m.Value)
				if (!row.edit) {

				}

			},
			async depertFun(roleID, row, e) {
				let data = {}
				data.roleID = roleID
				// key|部门编码,部门编码,部门编码_key|部门编码,部门编码,部门编码
				let str = ''
				let arr = []
				for (let i = 0, len = row.moduleList.length; i < len; i++) {
					arr.push(row.moduleList[i].Code)
				}
				arr.push(e)
				str = row.ModuleID + '|' + arr.join(',')
				let res = {};
				data.roleModule = str
				res = await ManageRoleModuleDoAddRoleModule(data);
				if (res.data.code === 0) {
					this.$message.success(res.data.msg);
					// this.closeFunction('1');
					this.GetListByKeyFun(roleID, row)
				} else {
					this.$message.error(res.data.msg);
				}
			},
			deleteList(roleID, row, item) {
				let that = this
				this.$confirm({
					title: '提示',
					content: '确定要删除该数据吗？',
					okText: '确认',
					cancelText: '取消',
					async onOk() {
						let data = {};
						data.roleID = roleID
						data.moduleID = row.ModuleID
						data.departCode = item.Code
						let res = {}
						res = await ManageRoleModuleDoDeleteRoleModule(data)
						if (res.data.code == 0) {
							that.GetListByKeyFun(roleID, row);
							that.$message.success(res.data.msg);
						} else {
							that.$message.error(res.data.msg);
						}
					}
				});

			},
			RoleCreditSendExamdeleteList(roleID, row, item) {
				let that = this
				this.$confirm({
					title: '提示',
					content: '确定要删除该数据吗？',
					okText: '确认',
					cancelText: '取消',
					async onOk() {
						let data = {};
						data.id = item.ID
						let res = {}
						res = await ManageRoleCreditSendExamDoDelete(data)
						if (res.data.code == 0) {
							that.RoleCreditSendExamFun(roleID, row);
							that.$message.success(res.data.msg);
						} else {
							that.$message.error(res.data.msg);
						}
					}
				});
			},
			deep(node) {
				let stack = node,
					data = [];
				while (stack.length != 0) {
					let pop = stack.pop();
					data.push({
						value: pop.value,
						title: pop.title,
						Pvalue: pop.Pvalue || '',
						BindKey: pop.BindKey || '',
						ModuleID: pop.Modulevalue || '',
						BindActivity: pop.BindActivity || '',
						BindActivityFlow: pop.BindActivityFlow || '',
						BindCreditFlow: pop.BindCreditFlow || '',
						BindPracticeFlow: pop.BindPracticeFlow || '',
						BindSendRecordExam: pop.BindSendRecordExam || '',
						BindActivityEndFlow: pop.BindActivityEndFlow || '',
						BindPracticeDeclareFlow: pop.BindPracticeDeclareFlow || '',
						BindClubAnnualAuditFlow: pop.BindClubAnnualAuditFlow || '',
					})
					let children = pop.children
					if (children) {
						for (let i = children.length - 1; i >= 0; i--) {
							stack.push(children[i])
						}
					}
				}
				return data
			},
			checkChange() {
				if (this.text.ID) {
					if (this.oldName != this.form.Name || this.oldPower != this.form.PowerData) {
						this.handleSubmit()
					}
				} else {
					this.handleSubmit()
				}
			},
			GetListByKeyActivityFun(roleID, row, name,title) {
				this.checkChange()
				this.modeltitle = title
				let that = this
				this.visible = true
				setTimeout(() => {
					// that.$router.push({
					// 	name: name,
					// 	query: {
					// 		roleID: roleID || that.text.ID
					// 	}
					// });
					let roleID1 = roleID || that.text.ID
					
					that.$nextTick(() => {
						that[name + 'If'] = true
						that.$refs[name+'1'].roleID = roleID1
						console.log(that.$refs[name+'1'])
						that.$refs[name+'1'].getList()
					})
					// console.log(that.$refs.RoleActivity1)
					// that.$refs.RoleActivity1.getList(roleID1)


				}, 500)


			},
			async RoleCreditSendExamFun(roleID, row, name) {
				this.checkChange()
				let res = await ManageRoleCreditSendExamDoGetList({
					roleID: roleID
				})
				row.BindSendRecordExamList = res.data.data
			},
			AddRoleCreditSendExamFun(roleID, row, name) {
				this.AddRoleCreditSendExamIf = true
				this.AddRoleCreditSendExamText = {
					RoleID: roleID,
					time: new Date()
				}
				this.roleID = roleID
				this.row = row
			},
			getMsgFormSon(data,num) {
				let ids = []
				let ids1 = []
				let ids2 = []
				for (let m = 0; m < data.length; m++) {
					for (let i = 0; i < this.treeDate.length; i++) {
						if (this.treeDate[i].value == data[m]) {
							ids1.push(data[m])
							for (let j = 0; j < this.treeDate[i].children.length; j++) {
								ids1.push(this.treeDate[i].children[j].value)
								for (let p = 0; p < this.treeDate[i].children[j].children.length; p++) {
									ids1.push(this.treeDate[i].children[j].children[p].value)
									for (let q = 0; q < this.treeDate[i].children[j].children[p].children.length; q++) {
										ids.push(this.treeDate[i].children[j].children[p].children[q].value)
									}
								}
							}
						} else {
							for (let j = 0; j < this.treeDate[i].children.length; j++) {
								if (this.treeDate[i].children[j].value == data[m]) {
									ids1.push(data[m])
									ids2.push(this.treeDate[i].value)
									for (let p = 0; p < this.treeDate[i].children[j].children.length; p++) {
										ids1.push(this.treeDate[i].children[j].children[p].value)
										for (let q = 0; q < this.treeDate[i].children[j].children[p].children
											.length; q++) {
											ids.push(this.treeDate[i].children[j].children[p].children[q].value)
										}
									}
								} else {
									for (let p = 0; p < this.treeDate[i].children[j].children.length; p++) {
										if (this.treeDate[i].children[j].children[p].value == data[m]) {
											ids1.push(data[m])
											ids2.push(this.treeDate[i].value)
											ids2.push(this.treeDate[i].children[j].value)
											for (let q = 0; q < this.treeDate[i].children[j].children[p].children
												.length; q++) {
												ids.push(this.treeDate[i].children[j].children[p].children[q].value)
											}
										} else {
											for (let q = 0; q < this.treeDate[i].children[j].children[p].children
												.length; q++) {
												if (this.treeDate[i].children[j].children[p].children[q].value == data[
														m]) {
													ids2.push(this.treeDate[i].value)
													ids2.push(this.treeDate[i].children[j].value)
													ids2.push(this.treeDate[i].children[j].children[p].value)
													ids.push(this.treeDate[i].children[j].children[p].children[q].value)
												}
											}
										}
									}
								}
							}
						}
					}
				}
				let arr = ids.concat(ids1)
				let arr1 = Array.from(new Set(arr))
				if(num!=1){
					this.form.PowerData = arr1.join(',')
				}
				this.tableFun(ids, ids1, ids2)
				// this.arrayToTree(arr3)
			},
			toTree(data) {
				let result = [];
				let map = {};
				if (!Array.isArray(data)) {
					return [];
				}
				data.forEach(item => {
					map[item.value] = item;
				});
				data.forEach(item => {
					let parent = map[item.Pvalue];
					if (parent) {
						if (parent.children && parent.children.find(e => e.value == item.value)) {

						} else {
							(parent.children || (parent.children = [])).push(item);
						}

					} else {
						result.push(item);
					}
				});
				return result;
			},
			closeFunction(data) {
				this.form = {
					Name: '',
					PowerData: ''
				}
				this.treetableDate = []
				this.treeValue = []
				this.$refs['ruleForm'].clearValidate();
				this.$emit('closeFun', this.changeData);
			},
			// closeFun(){
			// 	this.$emit('closeFun', '1');
			// },
			AddRoleCreditSendExamcloseFun() {
				this.AddRoleCreditSendExamIf = false
				this.RoleCreditSendExamFun(this.roleID, this.row)
			},
			handleSubmit(e) {
				this.$refs.ruleForm.validate(async valid => {
					if (valid) {
						let data = this.form;
						let res = {};
						if (JSON.stringify(this.text) == '{}') {
							res = await AddRole(data);
						} else {
							data.id = this.text.ID
							res = await UpdateRole(data);
						}
						if (res.data.code === 0) {
							this.changeData = 1
							this.$message.success(res.data.msg);
							this.text.ID = res.data.roleID
							this.oldName = res.data.roleName
							this.oldPower = res.data.rolePowerData
							this.closeFunction();
						} else {
							this.$message.error(res.data.msg);
							return false
						}
					} else {
						return false;
					}
				});
			},
			handleCancel() {
				console.log(22222)
				this.RoleCreditFlowIf = false
				this.RoleActivityManageIf = false
				this.RoleActivityIf = false
				this.RolePracticeTeamIf = false
				this.visible = false
			},
		}
	};
</script>

<style lang="less" scoped>
	.base {
		width: 80% !important;
		margin-left: -40% !important;
	}

	// .tanchuangcss{
	// 	background:#fff;
	// 	width:80%;
	// 	height:80%;
	// 	position: absolute;
	// 	left:50%;
	// 	top:10%;
	// 	margin-left:-40%;
	// 	padding:50px;
	// 	border:1px solid #ccc;
	// }

	.editbutton {
		margin-right: 4px;
		height: 24px;
		line-height: 24px;
		margin-left: 4px;
	}

	.list {
		border: 1px solid #ccc;
		padding: 2px 5px;
		border-radius: 6px;
		margin: 4px 6px 0 0;

		i {
			color: red;
			font-size: 14px;
			margin-left: 4px;
		}
	}

	.typelist {
		h4 {
			color: #4577EB;
			font-weight: bold;
			margin: 0px;
		}
	}
</style>
